package com.fh.utils.socket;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class WsSessionManager {
    /**
     * 保存连接 session 的地方
     */
    private final static ConcurrentHashMap<String,WebSocket> SESSION_POOL = new ConcurrentHashMap<>();

    /**
     * 添加 session
     */
    public static void add(String userId, WebSocket webSocket) {
        SESSION_POOL.put(userId, webSocket);
    }

    /**
     * 删除 session,会返回删除的 session
     */
    public static WebSocket remove(String userId) {
        return SESSION_POOL.remove(userId);
    }

    /**
     * 删除并同步关闭连接
     */
    public static void removeAndClose(String userId) {
        WebSocket webSocket = remove(userId);
        if (webSocket != null) {
            try {
                // 关闭连接
                webSocket.getSession().close();
                log.info("[removeAndClose] 关闭用户{}的WebSocket连接" , userId);
            } catch (IOException e) {
                log.error("关闭WebSocket连接异常：{}" , e.getMessage());
            }
        }
    }

    /**
     * 获得 session
     */
    public static WebSocket get(String userId) {
        return SESSION_POOL.get(userId);
    }
}
